package com.ktgj.common.log.aspect;


import com.ktgj.common.core.utils.ServletUtils;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.log.annotation.SignatureValidation;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class SignAspect {


    private static final Logger log = LoggerFactory.getLogger(SignAspect.class);
    /**
     * 时间戳请求最小限制(30s)
     * 设置的越小，安全系数越高，但是要注意一定的容错性
     */
    private static final long MAX_REQUEST = 30000000 * 1000L;
    private String SECRET = "KTGJ_jsj.com.cn";

    // 配置织入点
    @Pointcut("@annotation(com.ktgj.common.log.annotation.SignatureValidation)")
    public void signPointCut()
    {
    }

    @Before("signPointCut()")
    public void doBasicProfiling(final JoinPoint joinPoint) {
        SignatureValidation signatureValidation = getAnnotationSignature(joinPoint);
        if (signatureValidation == null) {
            return;
        }
        HttpServletRequest request = ServletUtils.getRequest();
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        if (!checkSignature(timestamp,sign)) {
            log.error("验签失败！");
            writeContent("验签失败！");
//            throw new RuntimeException("验签失败！");
        }
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "signPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {

    }

    public boolean checkSignature(String timestamp, String sign)
    {
        if (StringHelper.isNullOrEmpty(timestamp) || StringHelper.isNullOrEmpty(sign)) {
            return false;
        }
        long now = System.currentTimeMillis();
        long time = Long.parseLong(timestamp);
        if (now - time > MAX_REQUEST) {
            log.error("时间戳已过期[{}][{}][{}]", now, time, (now - time));
            writeContent(String.format("时间戳已过期[{%s}][{%s}]", longToDate(now), longToDate(time)));
            return false;
        }
        String signInfo = DigestUtils.md5Hex(SECRET + timestamp);
        if (!signInfo.equals(sign)) {
            log.error("签名不一致");
            writeContent("签名不一致");
            return false;
        }
        return true;
    }

    private void writeContent(String content) {
        HttpServletResponse response = ServletUtils.getResponse();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/plain;charset=UTF-8");
        response.setHeader("icop-content-type", "exception");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.print(content);
        writer.flush();
        writer.close();
        response.reset();
    }

    private SignatureValidation getAnnotationSignature(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(SignatureValidation.class);
        }
        return null;
    }

    /**
     * @Description: long类型转换成日期
     *
     * @param lo 毫秒数
     * @return String yyyy-MM-dd HH:mm:ss
     */
    public static String longToDate(long lo){
        Date date = new Date(lo);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);
    }

}
